<template>
  <div>
    <div>
      <h1>收货地址</h1>
      <el-table
          :data="address"
          ref="orderTable"
          @current-change="handleCurrentChange"
          tooltip-effect="light"
          highlight-current-row>
        <el-table-column
            label="选择"
            width="60"
            center>
          <template slot-scope="scope">
            <el-radio
                class="radio"
                v-model="radio"
                :label="scope.$index">
              &nbsp;</el-radio>
          </template>
        </el-table-column>
        <el-table-column
            width="220">
          <template slot-scope="scope">
            {{scope.row.name}}({{scope.row.telephone}})
          </template>
        </el-table-column>
        <el-table-column
            prop="city"
            width="300">
        </el-table-column>
        <el-table-column
            width="330"
            prop="address">
        </el-table-column>
      </el-table>
      <AddAddress :title="'+添加收货地址'"></AddAddress>
    </div>
    <div>
      <h1>商品清单</h1>
      <el-table
          stripe
          :data="goods">
        <el-table-column
            width="120">
          <template slot-scope="scope">
            <img :src="scope.row.picGoods" class="pic">
          </template>
        </el-table-column>
        <el-table-column
            width="500">
          <template slot-scope="scope">
            <h4>{{scope.row.goodsName}}</h4>
          </template>
        </el-table-column>
        <el-table-column>
          <template slot-scope="scope">
            {{scope.row.discount}}折
          </template>
        </el-table-column>
        <el-table-column>
          <template slot-scope="scope">
            {{scope.row.price}}￥
          </template>
        </el-table-column>
        <el-table-column>
          <template slot-scope="scope">
            ×{{scope.row.num}}件
          </template>
        </el-table-column>
        <el-table-column>
          <template slot-scope="scope">
            <h4>{{scope.row.price*scope.row.num}}￥</h4>
          </template>
        </el-table-column>
      </el-table>
      <div class="total">
        <h1 style="margin: 0;padding: 5px 0 0 30px;display: inline-block">总计</h1>
        <h3 style="display: inline-block;float: right;margin: 0;padding: 10px 40px 10px 0">{{totalPrice}}￥</h3>
      </div>
      <el-button
          type="danger"
          style="margin-top: 5px;float: right"
          @click="confirmMyOrder">确认并提交订单</el-button>
      <el-dialog
          :width="'500px'"
          title="确认支付"
          style="text-align: center"
          :visible.sync="confirmOrderDialog">
        <div>
          已有积分：<span style="color: red; font-size: 30px;margin-right: 15px;">{{integral}}</span>
          <el-checkbox v-model="checked" label="使用积分" border :disabled="checkdisabled"></el-checkbox>
          <span>(规则：100积分=1元)</span>
        </div>
        <div>
          是否确认支付<span style="color: red; font-size: 30px">{{actualPayPrice}}元</span>，支付后可获取<span style="color: red; font-size: 30px">{{actualPayPrice}}积分</span>
        </div>
        <el-button @click="confirmOrderDialog = false">取消</el-button>
        <el-button
            type="danger"
            style="margin-top: 30px"
            @click="pay">确认支付</el-button>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import AddAddress from '@/components/commons/addAddress'
export default {
  name: "settlement",
  components: {AddAddress},
  data() {
    return {
      radio: -1,
      address: [],
      currentRow: null,
      goods: [],
      confirmOrderDialog: false,
      bank: {},
      integral: 0,
      fIntegral: 0,
      checked: false
    }
  },
  computed: {
    totalPrice(){
      let sum = 0
      this.goods.forEach(good => {
        sum += good.price*good.num
      })
      return sum
    },
    actualPayPrice(){
      if(this.checked){
        this.fIntegral = this.integral
        return this.totalPrice - parseInt(this.fIntegral/100)
      }else{
        this.fIntegral = 0
        return this.totalPrice
      }
    },
    checkdisabled(){
      return this.integral < 100;
    }
  },
  methods: {
    handleCurrentChange(val){
      this.currentRow = val
      this.radio = this.address.findIndex(add => {
        return add.id === this.currentRow.id
      })
    },
    getAddress(){
      const userId = JSON.parse(sessionStorage.getItem("userInfo")).id
      this.$axios.get(`/address/${userId}`)
          .then(res => {
            this.address = res.data.data
          })
    },
    getCart(){
      let goodIds = this.$route.query.goodIds;
      let good = this.$route.params.good
      if(goodIds !== undefined){
        console.log(goodIds)
        const userId = JSON.parse(sessionStorage.getItem("userInfo")).id
        this.$axios.get(`/cart/${userId}`)
            .then(res => {
              this.goods = res.data.data.goods
              let nums = res.data.data.nums
              this.goods = this.goods.filter(good => {
                return goodIds.findIndex(item => good.id == item) != -1
              })
              this.goods.forEach((good, index) => {
                good.picGoods = "data:image/jpeg;base64,"+good.picGoods
                this.$set(good, "num", nums[index])
              })
            })
      }else{
        this.goods.unshift(good)
      }
    },
    setGoods(){
      this.goods.unshift(this.$route.params.good)
    },
    confirmMyOrder(){
      if(this.currentRow === null){
        this.$message.warning("请选择收货地址")
      }else{
        this.confirmOrderDialog = true
      }
    },
    pay(){
      if(this.bank.money >= this.actualPayPrice){
        const userId = JSON.parse(sessionStorage.getItem("userInfo")).id
        const addressId = this.currentRow !== null ? this.currentRow.id : this.address[0].id
        let data = []
        this.goods.forEach(good => {
          let d = {
            userId: userId,
            goodId: good.id,
            num: good.num,
            price: good.num * good.price,
            actualPrice: good.num * good.price - parseInt(this.fIntegral/100)/this.goods.length,
            addressId: addressId
          }
          data.unshift(d)
        })
        let goodIds = this.$route.query.goodIds;
        this.$axios.post("/addOrder", data)
            .then(res => {
              this.$message.success("提交成功")
              this.confirmOrderDialog = false
              this.changeMoney()
              if(goodIds !== undefined){
                this.deleteCart(data)
              }else{
                this.$router.push({
                  path: 'completed'
                })
              }
            })

      }else{
        this.$message.error("余额不足无法购买！！！")
      }
    },
    deleteCart(data){
      this.$axios.post("/deleteCart", data)
          .then(res => {
            this.$bus.$emit("deleteCart")
            this.$router.push({
              path: 'completed'
            })
          })
    },
    changeMoney(){
      const userId = JSON.parse(sessionStorage.getItem("userInfo")).id
      this.$axios.post("/changeMoney", {
        userId: userId,
        bankAccount: this.bank.bankAccount,
        money: this.actualPayPrice
      }).then(res => {
        this.useIntegral()
      })
    },
    getMoney(){
      const userId = JSON.parse(sessionStorage.getItem("userInfo")).id
      this.$axios.get(`/getMoney/${userId}`)
          .then(res => {
            this.bank = res.data.data
          })
    },
    getIntegral(){
      const userId = JSON.parse(sessionStorage.getItem("userInfo")).id
      this.$axios.get(`/getIntegral/${userId}`)
          .then(res => {
            this.integral = res.data.data
          })
    },
    useIntegral(){
      const userId = JSON.parse(sessionStorage.getItem("userInfo")).id
      this.$axios.post("/useIntegral", {
        userId: userId,
        number: parseInt(this.fIntegral/100)*100
      })
    }
  },
  mounted() {
    this.$bus.$on("addAddress1", () => {
      this.getAddress()
    })
  },
  created() {
    this.getAddress()
    this.getCart()
    this.getMoney()
    this.getIntegral()
  },
}
</script>

<style scoped>
.pic{
  width: 75px;
  display: inline-block;
}
.total{
  width: 100%;
  height: 45px;
  background-color: #F5F7FA;
}
</style>